package com.example.Arithmetic.Lettcode;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class E01Lettcode819_2 {
    public String mostCommonWord(String paragraph, String[] banned) {
        Set<String> set = Set.of(banned);
        HashMap<String, Integer> hashMap = new HashMap<>();
        char[] chars = paragraph.toLowerCase().toCharArray();
        StringBuilder stringBuilder = new StringBuilder();

        for (char c : chars) {
            if (c >= 'a' && c <= 'z') {
                stringBuilder.append(c);
            } else if (stringBuilder.length() > 0) {
                String s = stringBuilder.toString();
                if (!set.contains(s)) {
                    hashMap.compute(s, (k, v) -> v == null ? 1 : v + 1);
                }
                stringBuilder.setLength(0);
            }
        }

        // 处理最后一个单词
        if (stringBuilder.length() > 0) {
            String s = stringBuilder.toString();
            if (!set.contains(s)) {
                hashMap.compute(s, (k, v) -> v == null ? 1 : v + 1);
            }
        }

        int max = 0;
        String key = null;
        for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
            Integer value = entry.getValue();
            if (value > max) {
                max = value;
                key = entry.getKey();
            }
        }
        return key;
    }

    public static void main(String[] args) {
        E01Lettcode819_2 solution = new E01Lettcode819_2();

        String paragraph = "Bob. hIt, baLl";
        String[] banned = {"bob", "hit"};

        String result = solution.mostCommonWord(paragraph, banned);
        System.out.println("Actual Result: " + result);
    }
}
